package com.bosssoft.trainee.nontax.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bosssoft.trainee.nontax.common.Result;
import com.bosssoft.trainee.nontax.entity.po.Role;
import com.bosssoft.trainee.nontax.entity.po.RolePermission;
import com.bosssoft.trainee.nontax.entity.po.UserRole;
import com.bosssoft.trainee.nontax.mapper.PermissionMapper;
import com.bosssoft.trainee.nontax.mapper.RoleMapper;
import com.bosssoft.trainee.nontax.service.IRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MaYunFei
 * @ProjectName RBAC_BOSS
 * @Description TODO
 * @time 2022/6/13 15:53
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    RoleMapper roleMapper;

    @Resource
    PermissionMapper permissionMapper;

    @Override
    public void changePermission(Role role) {
        // 先根据角色id删除所有的角色跟权限的绑定关系
        permissionMapper.deletePermissionsByRoleId(role.getId());
        // 再新增 新的绑定关系
        for (Integer permissionId : role.getPermissions()) {
            permissionMapper.insertRoleAndPermission(role.getId(), permissionId);
        }
    }

    @Override
    public List<UserRole> getUserRoleByUserId(Integer id) {
        return roleMapper.getUserRoleByUserId(id);
    }

    @Override
    public Result<?> findPage(Integer pageNum, Integer pageSize, String search) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Role::getName, search);
        }
        Page<Role> RolePage = roleMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        List<Role> records = RolePage.getRecords();
        // 给角色设置绑定的权限id数组
        for (Role record : records) {
            Integer roleId = record.getId();
            List<Integer> permissions = permissionMapper.getRolePermissionByRoleId(roleId).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
            record.setPermissions(permissions);
        }
        return Result.success(RolePage);
    }
}
